package org.example.juc;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class UnsafeTest {

    public volatile int count = 0;

    public static Unsafe unsafe;

    public long countOffset;

    public AtomicInteger counter = new AtomicInteger(0);

    public UnsafeTest() {
        try {

            // 只能通过字段获取
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);

            // 计算字段在对象的地址
            Field countOffsetField = UnsafeTest.class.getField("count");
            countOffsetField.setAccessible(true);
            countOffset = unsafe.objectFieldOffset(countOffsetField);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自增
     */
    public void increment() {
        // 不断的自旋
        for (; ; ) {
            boolean flag = unsafe.compareAndSwapInt(this, countOffset, count, count + 1);
            if (flag) {
                break;
            }
        }
    }

    /**
     * 自减
     */
    public void decrement() {
        for (; ; ) {
            boolean flag = unsafe.compareAndSwapInt(this, countOffset, count, count - 1);
            if (flag) {
                break;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        // 10个线程，每个线程1000次
        CountDownLatch latch = new CountDownLatch(10);
        ExecutorService service = Executors.newFixedThreadPool(10);

        UnsafeTest test = new UnsafeTest();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) {
//                        test.counter.getAndIncrement();
                         test.increment();
                    }
                    latch.countDown();
                }
            });
        }

        latch.await();
        System.out.println("count = " + test.counter.get());
        System.out.println("count = " + test.count);
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
    }
}
